/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package XMLManipulator;

import java.io.File;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 *
 * @author Phuong Giang
 */
public class XMLDealer {

    public synchronized static Object Read(Class classBound, String filePath) {
        try {
            JAXBContext ctx = JAXBContext.newInstance(classBound);
            Unmarshaller un = ctx.createUnmarshaller();
            File XMLfile = new File(filePath);
            return un.unmarshal(XMLfile);
        } 
        catch (JAXBException ex) {
            Logger.getLogger(XMLDealer.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public synchronized  static void Write(Class classBound, String filePath, Object object2write) {
        try {
            JAXBContext ctx = JAXBContext.newInstance(classBound);
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(object2write, new File(filePath));
        } 
        catch (JAXBException ex) {
            Logger.getLogger(XMLDealer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void Write(Class classBound, OutputStream output, Object object2write) {
        try {
            JAXBContext ctx = JAXBContext.newInstance(classBound);
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(object2write, output);
        } 
        catch (JAXBException ex) {
            Logger.getLogger(XMLDealer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
